package com.huichenghe.xinlvsh01.slide;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.huichenghe.xinlvsh01.CustomView.CircleImageView;
import com.huichenghe.xinlvsh01.DataEntites.RegistDataEntity;
import com.huichenghe.xinlvsh01.MainActivity;
import com.huichenghe.xinlvsh01.R;
import com.huichenghe.xinlvsh01.Utils.DataSecletor.NumericWheelAdapter;
import com.huichenghe.xinlvsh01.Utils.DataSecletor.OnWheelScrollListener;
import com.huichenghe.xinlvsh01.Utils.DataSecletor.WheelView;
import com.huichenghe.xinlvsh01.Utils.EditorPhotoUtils;
import com.huichenghe.xinlvsh01.Utils.LocalDataSaveTool;
import com.huichenghe.xinlvsh01.Utils.MyConfingInfo;
import com.huichenghe.xinlvsh01.Utils.MyToastUitls;
import com.huichenghe.xinlvsh01.Utils.SaveImageUtil;
import com.huichenghe.xinlvsh01.Utils.WebGlobalConfig;
import com.huichenghe.xinlvsh01.http.HttpUtil;
import com.lidroid.xutils.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.Buffer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class EditPersionInfoActivity extends AppCompatActivity {
    public static final String TAG = EditPersionInfoActivity.class.getSimpleName();
    private CoordinatorLayout mCoordinatorLayout;
    private RelativeLayout editPersionInfoLayout;
    private RelativeLayout showPersionInfoLayout;
    private ImageButton fabY;
    private ImageButton fabN;
    private ImageView takePortrait; // 编辑布局，圆形头像控件
    private EditText nickName, email, height, weight;
    private TextView birthday;
    private RadioGroup group;
    private RadioButton male, female;
    private int gender;
    private String ACCOUNT = "user.account";
    private String EMAIL = "user.email";
    private String PASSWORD = "user.password";
    private String NICK = "user.nick";
    private String BIRTHDAY = "user.birthdate";
    private String GENDER = "user.gender";
    private String HEIGHT = "user.height";
    private String WEIGHT = "user.weight";
    private String HEADER = "header";

    private CircleImageView showPortran;        // 头像
    private TextView emailS, birthdayS, heightS, weightS, nickS;
    private RadioButton mMale, mFemale;
    private boolean regist;     // 注册时编辑资料
    private boolean editPersionInfo;// 修改时编辑资料
    private boolean editPersionFirst;// 直接进入时编辑资料
    private boolean editFirst;


    String accounta = null;         // 用户输入的用户名
    String pwdd = null;             // 用户输入密码
    Toolbar toolbar;





    String or;      // 代表意图；
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_persion_info);

        regist = getIntent().getBooleanExtra(MyConfingInfo.REGIST, false);
        editPersionInfo = getIntent().getBooleanExtra(MyConfingInfo.EDIT_PERSION, false);

        mCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
        int statusBar = getStatusBarHeight();
        mCoordinatorLayout.setPadding(0, statusBar, 0, 0);
        settingTheStatebarAndNavigationbar();
        init();
        or = getIntent().getStringExtra(MyConfingInfo.EDIT_OR_SHOW);
        if (or.equals(MyConfingInfo.EDIT_PERSION_INFO))
        {
            editPersionInfoLayout.setVisibility(View.VISIBLE);
            if(fabN.getVisibility() == View.VISIBLE)
            {
                fabN.setVisibility(View.GONE);
            }
        }
        else
        {
            editPersionInfoLayout.setVisibility(View.GONE);
        }




        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
//        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 读取缓存的个人资料并显示
        Bitmap mBitmap = SaveImageUtil.readImageFormSD(MyConfingInfo.IMAGEVIEW_SAVE_PATH + File.separator + "tmp.jpeg");
        if(mBitmap != null)
        {
            showPortran.setImageBitmap(mBitmap);
            if(!regist)     // 不是注册
            {
                // 编辑页面显示头像
                takePortrait.setImageBitmap(mBitmap);
            }

        }

        String nic = getContent(MyConfingInfo.USER_NICK);
        String eml = getContent(MyConfingInfo.USER_EMAIL);
        String bir = getContent(MyConfingInfo.USER_BIRTHDAY);
        String hei = getContent(MyConfingInfo.USER_HEIGHT);
        String wei = getContent(MyConfingInfo.USER_WEIGHT);
        showText(nickS, nic);
        showText(emailS, eml);
        showText(birthdayS, bir);
        showText(heightS, hei);
        showText(weightS, wei);
        String gender = LocalDataSaveTool.getInstance(EditPersionInfoActivity.this).readSp(MyConfingInfo.USER_GENDER);
        if(gender.equals("1"))
        {
            mMale.setChecked(true);
            if(!regist)
            {
                male.setChecked(true);
            }
        }
        else
        {
            mFemale.setChecked(true);
            if(!regist)
            {
                female.setChecked(true);
            }
        }

        if(!regist)
        {
            showEditText(nickName, nic);
            showEditText(email, eml);
            showText(birthday, bir);
            showEditText(height, hei);
            showEditText(weight, wei);

        }





    }

    private String getContent(String s)
    {
        return LocalDataSaveTool.getInstance(EditPersionInfoActivity.this).readSp(s);
    }

    /**
     * 显示指定控件，指定内容
     * @param tv
     * @param content
     */
    private void showText(TextView tv, String content)
    {
        if(tv != null && content != null)
        {
            tv.setText(content);
        }

    }


    private void showEditText(EditText et, String content)
    {
        if(et != null && content != null)
        {
            et.setText(content);
        }
    }

    /**
     * 获取状态栏的高度
     */
    private int getStatusBarHeight() {
        int result = 0;
        int resurcedId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resurcedId > 0) {
            result = getResources().getDimensionPixelSize(resurcedId);
        }

        return result;
    }

    /**
     * 设置导航栏和底部虚拟件全屏
     */
    private void settingTheStatebarAndNavigationbar() {
        // 透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //底部虚拟键透明
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }


    /**
     * 初始化界面对象并监听处理
     */
    private void init() {
        showPortran = (CircleImageView)findViewById(R.id.show_portrait);
        nickS = (TextView)findViewById(R.id.nick_show_persioninfo);
        emailS = (TextView)findViewById(R.id.email_show_persioninfo);
        birthdayS = (TextView)findViewById(R.id.show_birthday_persioninfo);
        heightS = (TextView)findViewById(R.id.show_height_persioninfo);
        weightS = (TextView)findViewById(R.id.show_weight_persioninfo);
        mMale = (RadioButton)findViewById(R.id.show_male);
        mFemale = (RadioButton)findViewById(R.id.show_female);


        group = (RadioGroup) findViewById(R.id.group_layout);
        // 设置选项监听
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.male:
                        gender = 1;
                        break;
                    case R.id.female:
                        gender = 2;
                        break;
                }
            }
        });
        male = (RadioButton) findViewById(R.id.male);
        male.setChecked(true);
        female = (RadioButton) findViewById(R.id.female);
        nickName = (EditText) findViewById(R.id.nick_name);
        email = (EditText) findViewById(R.id.input_email);
        birthday = (TextView) findViewById(R.id.input_birthday);
        birthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 显示悬浮窗，窗内显示日期选择
                showPopwindow(getDataPick());
            }
        });
        height = (EditText) findViewById(R.id.edit_height);
        weight = (EditText) findViewById(R.id.edit_weight);


        toolbar = (Toolbar) findViewById(R.id.persioniffo_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // toolbar监听返回键
        toolbar.setNavigationIcon(R.drawable.back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {   // 关闭页面
                EditPersionInfoActivity.this.onBackPressed();
            }
        });
        // 菜单监听处理
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_edit_persion_info:
                        // 判断sdk版本
                        if(Build.VERSION.SDK_INT < 21)
                        {
                            editPersionInfoLayout.setVisibility(View.VISIBLE);
                        }
                        else
                        {
                            // 执行圆形动画
                            int cx = editPersionInfoLayout.getWidth();  // 圆心x轴
                            int cy = 0;                                 // 圆心y轴

                            // get the final radius for the clipping circle
                            int finalRadius = Math.max(editPersionInfoLayout.getWidth(), editPersionInfoLayout.getHeight());

                            // create the animator for this view (the start radius is zero)
                            Animator anim =
                                    ViewAnimationUtils.createCircularReveal(editPersionInfoLayout, cx, cy / 2, 0, finalRadius);

                            // make the view visible and start the animation
                            editPersionInfoLayout.setVisibility(View.VISIBLE);
                            anim.start();
//                        showPersionInfoLayout.setVisibility(View.INVISIBLE);
//                        fabN.hide();
                        }





                        break;
                }

                return true;
            }
        });


        // 悬浮按钮
        fabY = (ImageButton) findViewById(R.id.fab_ok);
        fabY.setOnClickListener(myListener);
        fabN = (ImageButton) findViewById(R.id.fab_cancle);
        fabN.setOnClickListener(myListener);

        // 头像
        takePortrait = (ImageView) findViewById(R.id.take_portrait);
        takePortrait.setOnClickListener(myListener);

        // 编辑个人信息布局
        editPersionInfoLayout = (RelativeLayout) findViewById(R.id.edit_persion_info_layout);
        // 显示个人信息布局
        showPersionInfoLayout = (RelativeLayout) findViewById(R.id.show_persioninfo_layout);


    }

    /**
     * 显示日期选择器
     *
     * @param dataPick
     */
    private void showPopwindow(View dataPick) {
        // 构建悬浮窗
        mPopupWindow = new PopupWindow(dataPick, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setOutsideTouchable(false);
        // 设置焦点
        mPopupWindow.setFocusable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.showAtLocation(dataPick, Gravity.CENTER_HORIZONTAL, 0, 0);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mPopupWindow = null;
            }
        });
    }

    private EditorPhotoUtils editorPhotoUtil;

    /**
     * 监听dialog的item
     */
    DialogInterface.OnClickListener dialogListener = new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
                case 0:         // 拍照
                    editorPhotoUtil = new EditorPhotoUtils(EditPersionInfoActivity.this, takePortrait);
                    editorPhotoUtil.onTakePhotoChosen();
                    break;
                case 1:         // 从相册选择
                    EditorPhotoUtils editorPhotoUtils = new EditorPhotoUtils(EditPersionInfoActivity.this, new ImageView(EditPersionInfoActivity.this));
                    editorPhotoUtils.onPickFromGalleryChosen();
                    break;
                case 2:
                    dialog.dismiss();
                    break;
            }

        }
    };
    Bitmap mBitmap = null;

    /**
     * startActivityforResult,通过调用此方法回传数据
     *
     * @param requestCode // 响应码
     * @param resultCode  // 结果码
     * @param data        // 数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mBitmap = data.getParcelableExtra("data");
        editorPhotoUtil.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 处理监听事件
     */
    View.OnClickListener myListener = new View.OnClickListener() {
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onClick(View v) {
            switch (v.getId()) {   // 点击头像,弹出对话框
                case R.id.take_portrait:
                    AlertDialog.Builder dialog = new AlertDialog.Builder(EditPersionInfoActivity.this);
//                    dialog.setSingleChoiceItems(new String[]{"拍照", "从本地相册选择", "取消"}, 0, null);
//                    dialog.create().show();
                    dialog.setItems(new String[]{getString(R.string.take_photo_action),
                            getString(R.string.selecte_from_local),
                            getString(R.string.cancle)}, dialogListener);
                    dialog.setCancelable(false);
                    dialog.create().show();


                    break;
                case R.id.fab_ok:
                    // 点击注册完成按钮
                    // 检查输入内容
                    Toast.makeText(EditPersionInfoActivity.this, getString(R.string.persion_info_check), Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "--------检查输入内容-------");
                    boolean isOk = checkTheInputContent();  // 校验是否通过
                    if(!isOk)return;
                    if(regist)      // 注册
                    {
                        Toast.makeText(EditPersionInfoActivity.this, getString(R.string.regist_now), Toast.LENGTH_LONG).show();
                        registNow(emailN, birthdayN, nickN, heightN, weightN);
                    }


                    if(editPersionInfo) // 修改资料
                    {
//                        Toast.makeText(EditPersionInfoActivity.this, getString(R.string.modify_persion_info), Toast.LENGTH_SHORT).show();
                        midifyNow(emailN, birthdayN, nickN, heightN, weightN);

                    }
                    String first = getIntent().getStringExtra(MyConfingInfo.EDIT_OR_SHOW);
                    if(first.equals(MyConfingInfo.EDIT_PERSION_INFO))
                    {
                        editFirst = true;
                    }
                    if(editFirst)
                    {
                        savePersionToSP(nickN, emailN, birthdayN, heightN, weightN, gender);
                        Intent intent = new Intent();
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setClass(EditPersionInfoActivity.this, MainActivity.class);
                        startActivity(intent);
                    }




//                    if (or.equals(MyConfingInfo.EDIT_PERSION_INFO)) {
//                        if (isOk) {
//                            // 代表首次填写资料，直接进入主页
//                            Intent mIntent = new Intent();
//                            mIntent.setClass(EditPersionInfoActivity.this, MainActivity.class);
//                            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                            startActivity(mIntent);
//                        }
//
//                    } else {
//                        Snackbar.make(v, getString(R.string.persion_info_edit_ok), Snackbar.LENGTH_LONG)
//                                .setAction("Action", null).show();
//                        int cxx = editPersionInfoLayout.getWidth();
//                        int cyy = 0;
//
//                        // get the initial radius for the clipping circle
//                        // 获取园的半径
//                        int initialRadiuss = editPersionInfoLayout.getWidth();
//
//                        // create the animation (the final radius is zero)
//                        Animator anims =
//                                ViewAnimationUtils.createCircularReveal(editPersionInfoLayout, cxx, cyy, initialRadiuss, 0);
//
//                        // make the view invisible when the animation is done
//                        anims.addListener(new AnimatorListenerAdapter() {
//                            @Override
//                            public void onAnimationEnd(Animator animation) {
//                                super.onAnimationEnd(animation);
//                                editPersionInfoLayout.setVisibility(View.INVISIBLE);
//                            }
//                        });
//
//                        // start the animation
//                        anims.start();
//
////                    showPersionInfoLayout.setVisibility(View.VISIBLE);
//                    }


                    break;

                case R.id.fab_cancle:



                    if(!regist)
                    {


                    // previously visible view  控件隐藏动画
//                    final View myView = findViewById(R.id.my_view);

                    // get the center for the clipping circle
                    // 获取园的中心
                    int cx = editPersionInfoLayout.getWidth();
                    int cy = 0;

                    // get the initial radius for the clipping circle
                    // 获取园的半径
                    int initialRadius = editPersionInfoLayout.getWidth();

                    // create the animation (the final radius is zero)
                    Animator anim =
                            ViewAnimationUtils.createCircularReveal(editPersionInfoLayout, cx, cy, initialRadius, 0);

                    // make the view invisible when the animation is done
                    anim.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            super.onAnimationEnd(animation);
                            editPersionInfoLayout.setVisibility(View.INVISIBLE);
                        }
                    });

                    // start the animation
                    anim.start();

//                    showPersionInfoLayout.setVisibility(View.VISIBLE);
                    }
                    else
                    {
                        EditPersionInfoActivity.this.onBackPressed();
                    }

                    break;
            }
        }
    };


    /**
     * 修改用户资料
     * @param emailN
     * @param birthdayN
     * @param nickN
     * @param heightN
     * @param weightN
     */
    private void midifyNow(String emailN, String birthdayN, String nickN, String heightN, String weightN)
    {
        boolean hasImage = false;
        // 判断是否有图片
        File file = new File(MyConfingInfo.IMAGEVIEW_SAVE_PATH);
        if(file.exists())
        {
            hasImage = true;
        }

        modifyAsync asy = new modifyAsync(emailN, birthdayN, nickN, heightN, weightN, MyConfingInfo.IMAGEVIEW_SAVE_PATH, file, hasImage);
        asy.execute((Void)null);



    }


    /**
     * 修改资料异步任务
     */
    public class modifyAsync extends AsyncTask<Void, Void, Boolean>
    {
        private String emailM, birthdayM, nickM, heightM, weightM, pathM;
        private boolean hasImage;
        private File mFile;
        private HashMap<String, String> dataMap;    // 字符形内容map
        private HashMap<String[], File> fileMap;    // 文件型内容的map
        private String[] mm = new String[3];

        public modifyAsync(String emailM, String birthdayM, String nickM,
                           String heightM, String weightM, String path,
                           File mFile, boolean hasImage)
        {
            this.emailM = emailM;
            this.birthdayM = birthdayM;
            this.nickM = nickM;
            this.heightM = heightM;
            this.weightM = weightM;
            this.pathM = path;
            this.hasImage = hasImage;
            this.mFile = mFile;

            dataMap = new HashMap<String, String>();
            dataMap.put(EMAIL, emailM);
            dataMap.put(NICK, nickM);
            dataMap.put(BIRTHDAY, birthdayM);
            dataMap.put(GENDER, gender + "");
            dataMap.put(HEIGHT, heightM);
            dataMap.put(WEIGHT, weightM);

            mm[0] = path;
            mm[1] = "image/jpeg";
            mm[2] = HEADER;

            fileMap = new HashMap<String[], File>();
            fileMap.put(mm, mFile);
        }

        @Override
        protected Boolean doInBackground(Void... params)
        {
            String u = MyConfingInfo.WebRequeModify;

            try {
                String cookie = LocalDataSaveTool.getInstance(EditPersionInfoActivity.this).readSp(MyConfingInfo.COOKIE_FOR_ME);
                Log.i(TAG, "保存的cookie:" + cookie);
                HttpUtil.postDataAndImageHaveCookie(hasImage, u, dataMap, fileMap, cookie, new HttpUtil.DealResponse() {
                    @Override
                    public void dealResponse(int responseCode, InputStream input) throws IOException {
                        String result = "";
                        InputStreamReader re = new InputStreamReader(input);
                        BufferedReader reader = new BufferedReader(re);
                        String c = null;
                        while ((c = reader.readLine()) != null) {
                            result = result + c;
                        }

                        Log.i(TAG, "修改资料的结果：" + result);
                        JSONObject json = null;
                        try {
                            json = new JSONObject(result);
                            String code = json.getString("code");
                            if(code.equals("9003"))
                            {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        MyToastUitls.showToast(EditPersionInfoActivity.this, R.string.modify_persion_ok, 2);
                                        LocalDataSaveTool.getInstance(EditPersionInfoActivity.this).writeSp(MyConfingInfo.PERSION_HAS_CHANGER, "1");
                                        // 存储个人信息
                                        savePersionToSP(nickM, emailM, birthdayM, heightM, weightM, gender);

                                        // 隐藏编辑个人信息布局
                                        inVisibaleCurrentLayout();

                                        // 更新个人信息布局

                                        updatePersionInfo(nickM, emailM, birthdayM, heightM, weightM, gender);



                                    }
                                });
                            }
                            else
                            {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        LocalDataSaveTool.getInstance(EditPersionInfoActivity.this).writeSp(MyConfingInfo.PERSION_HAS_CHANGER, "0");
                                        MyToastUitls.showToast(EditPersionInfoActivity.this, R.string.modify_persion_failed, 2);
                                    }
                                });
                            }





                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }

                    @Override
                    public void setHeader(String url, Object obj) {

                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }


            return null;
        }


        /**
         * 修改资料后更新个人信息
         * @param nickM
         * @param emailM
         * @param birthdayM
         * @param heightM
         * @param weightM
         * @param gender
         */
        private void updatePersionInfo(String nickM, String emailM, String birthdayM,
                                       String heightM, String weightM, int gender)
        {
            // 更新头像
            Bitmap bitmap = SaveImageUtil.readImageFormSD(MyConfingInfo.IMAGEVIEW_SAVE_PATH + File.separator + "tmp.jpeg");
            showPortran.setImageBitmap(bitmap);

            // 更新其他资料

            showText(nickS, nickM);
            showText(emailS, emailM);
            showText(birthdayS, birthdayM);
            showText(heightS, heightM);
            showText(weightS, weightM);
            String genderM = LocalDataSaveTool.getInstance(EditPersionInfoActivity.this).readSp(MyConfingInfo.USER_GENDER);
            if(genderM.equals("1"))
            {
                mMale.setChecked(true);
            }
            else
            {
                mFemale.setChecked(true);
            }




        }


        /**
         * 隐藏编辑个人信息布局
         */
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        private void inVisibaleCurrentLayout()
        {
            int cxx = editPersionInfoLayout.getWidth();
            int cyy = 0;

                        // get the initial radius for the clipping circle
                        // 获取园的半径
            int initialRadiuss = editPersionInfoLayout.getHeight();

                        // create the animation (the final radius is zero)
            Animator anims =
                    ViewAnimationUtils.createCircularReveal(editPersionInfoLayout, cxx, cyy, initialRadiuss, 0);

                        // make the view invisible when the animation is done
             anims.addListener(new AnimatorListenerAdapter() {
                   @Override
                   public void onAnimationEnd(Animator animation) {
                                super.onAnimationEnd(animation);
                                editPersionInfoLayout.setVisibility(View.INVISIBLE);
                            }
                        });

                        // start the animation
                        anims.start();

                    showPersionInfoLayout.setVisibility(View.VISIBLE);

        }


        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
        }
    }


    String nickN;
    String emailN;
    String birthdayN;
    String heightN;
    String weightN;

    /**
     * 获取并校验输入内容
     */
    private boolean checkTheInputContent() {
        nickN = nickName.getText().toString();       // 昵称
        emailN = email.getText().toString();         // email
        birthdayN = birthday.getText().toString();   // birthday
        heightN = height.getText().toString();       // 身高
        weightN = weight.getText().toString();       // 体重

        boolean empty = false;
        View thisView = null;
        ArrayList<EditText> list = new ArrayList<EditText>();
        list.add(nickName);
        list.add(email);
        list.add(height);
        list.add(weight);
        for (int i = 0; i < list.size(); i++) {
            EditText editText = list.get(i);
            String info = editText.getText().toString();
            // 非空验证
            if (info.isEmpty()) {
                editText.setError(getString(R.string.not_null));
                empty = true;
                thisView = editText;
            }
        }


        if (birthdayN.isEmpty()) {
            birthday.setError(getString(R.string.not_null));
            empty = true;
            thisView = birthday;
        }

        if (empty) {
            thisView.requestFocus();
            return false;
        }

        // 判断昵称上限
        if (nickN.length() > 32) {
            nickName.setError(getString(R.string.nick_name_short_or_long));
            empty = true;
            thisView = nickName;
        }

        if (!emailN.contains("@") || emailN.length() > 74) {
            email.setError(getString(R.string.email_wrong));
            empty = true;
            thisView = email;
        }


        // 判断身高
        if (Integer.parseInt(heightN) < 40 || Integer.parseInt(heightN) > 250) {
            height.setError(getString(R.string.height_wrong));
            empty = true;
            thisView = height;
        }

        if (Integer.parseInt(weightN) < 30 || Integer.parseInt(weightN) > 200) {
            weight.setError(getString(R.string.weight_wrong));
            empty = true;
            thisView = weight;
        }

        if (empty) {
            thisView.requestFocus();
            return false;
        }



        Log.i(TAG, "--------检查完毕-------");



        // 存入缓存
//        savePersionToSP(nickN, emailN, birthdayN, heightN, weightN, gender, accounta, pwdd);


        return true;

    }

    private boolean registNow(String emailN, String birthdayN, String nickN, String heightN, String weightN)
    {
        if (regist)
        {
            boolean haveImage = false;      // 标识是否有图片
            accounta = getIntent().getStringExtra(MyConfingInfo.USER_ACCOUNT);  // intent传递过来的账号和密码
            pwdd = getIntent().getStringExtra(MyConfingInfo.USER_PASSWORD);
//            从内存卡读取图片
            String path = null;
            File file = new File(MyConfingInfo.IMAGEVIEW_SAVE_PATH);
            if(file.exists())   // 判断有无图片
            {
                path = MyConfingInfo.IMAGEVIEW_SAVE_PATH;
                haveImage = true;
            }


            // 执行异步注册
            Log.i(TAG, "--------执行异步任务-------");

            String pwd = WebGlobalConfig.get32MD5Str(pwdd); // MD5加密
            RegistTask task = new RegistTask(accounta, pwd, emailN, birthdayN, nickN, heightN, weightN, gender + "", path, file, haveImage);
            task.execute();



        }
        return false;
    }


    /**
     * 读取图片
     *
     * @param file
     */
    private Bitmap readBitmapFromSd(File file) {
        Bitmap mBitmap = BitmapFactory.decodeFile(String.valueOf(file));
        return mBitmap;
    }

    @Override
    public void onStart() {
        super.onStart();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
//        client.connect();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
//        client.connect();
//        Action viewAction = Action.newAction(
//                Action.TYPE_VIEW, // TODO: choose an action type.
//                "EditPersionInfo Page", // TODO: Define a title for the content shown.
//                // TODO: If you have web page content that matches this app activity's content,
//                // make sure this auto-generated web page URL is correct.
//                // Otherwise, set the URL to null.
//                Uri.parse("http://host/path"),
//                // TODO: Make sure this auto-generated app deep link URI is correct.
//                Uri.parse("android-app://com.huichenghe.xinlvsh01.slide/http/host/path")
//        );
//        AppIndex.AppIndexApi.start(client, viewAction);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
//        Action viewAction = Action.newAction(
//                Action.TYPE_VIEW, // TODO: choose an action type.
//                "EditPersionInfo Page", // TODO: Define a title for the content shown.
//                // TODO: If you have web page content that matches this app activity's content,
//                // make sure this auto-generated web page URL is correct.
//                // Otherwise, set the URL to null.
//                Uri.parse("http://host/path"),
//                // TODO: Make sure this auto-generated app deep link URI is correct.
//                Uri.parse("android-app://com.huichenghe.xinlvsh01.slide/http/host/path")
//        );
//        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
//        Action viewAction = Action.newAction(
//                Action.TYPE_VIEW, // TODO: choose an action type.
//                "EditPersionInfo Page", // TODO: Define a title for the content shown.
//                // TODO: If you have web page content that matches this app activity's content,
//                // make sure this auto-generated web page URL is correct.
//                // Otherwise, set the URL to null.
//                Uri.parse("http://host/path"),
//                // TODO: Make sure this auto-generated app deep link URI is correct.
//                Uri.parse("android-app://com.huichenghe.xinlvsh01.slide/http/host/path")
//        );
//        AppIndex.AppIndexApi.end(client, viewAction);

//        // ATTENTION: This was auto-generated to implement the App Indexing API.
//        // See https://g.co/AppIndexing/AndroidStudio for more information.
//        Action viewAction = Action.newAction(
//                Action.TYPE_VIEW, // TODO: choose an action type.
//                "EditPersionInfo Page", // TODO: Define a title for the content shown.
//                // TODO: If you have web page content that matches this app activity's content,
//                // make sure this auto-generated web page URL is correct.
//                // Otherwise, set the URL to null.
//                Uri.parse("http://host/path"),
//                // TODO: Make sure this auto-generated app deep link URI is correct.
//                Uri.parse("android-app://com.huichenghe.xinlvsh01.slide/http/host/path")
//        );
//        AppIndex.AppIndexApi.end(client, viewAction);
//        client.disconnect();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
//        client.disconnect();
    }


    private void login_Now(String accounta, String pwdd)
    {
        boolean isLoginSuccess = false;
        Sub_login toLogin = new Sub_login(EditPersionInfoActivity.this);
        try {
            isLoginSuccess = toLogin.requestLogin(accounta, pwdd);      // 返回true登陆成功
        } catch (IOException e) {
            e.printStackTrace();
        }
            if(isLoginSuccess)
            {
                Bitmap mBitmap =  toLogin.getImageIcon();               // 登陆成功，获取图片
                SaveImageUtil.saveImageToSD(mBitmap, MyConfingInfo.IMAGEVIEW_SAVE_PATH, File.separator + "tmp.jpeg");// 保存图片到sd卡
                // 保存账号密码
                LocalDataSaveTool.getInstance(EditPersionInfoActivity.this).writeSp(MyConfingInfo.USER_ACCOUNT, accounta);
                LocalDataSaveTool.getInstance(EditPersionInfoActivity.this).writeSp(MyConfingInfo.USER_PASSWORD, pwdd);

                // 打开主界面
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent();
                        intent.setClass(EditPersionInfoActivity.this, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);

                        EditPersionInfoActivity.this.onBackPressed();
                    }
                });


            }



    }


    /**
     * 异步发送注册数据
     */
    class RegistTask extends AsyncTask<Void, Void, Boolean>
    {
        public final String TAG = EditPersionInfoActivity.class.getSimpleName();
        private HashMap<String, String> hashMap;
        private HashMap<String[], File> fileMap;
        String[] hh = new String[3];



        String content;
        boolean haveImage = false;


        public RegistTask(String account,
                          String password,
                          String email,
                          String birthday,
                          String nickName,
                          String height,
                          String weight,
                          String gender,
                          String path,
                          File mFile,
                          boolean haveImage)
        {
            this.haveImage = haveImage;
            hashMap = new HashMap<String, String>();
            hashMap.put(ACCOUNT, account);
            hashMap.put(EMAIL, email);
            hashMap.put(PASSWORD, password);
            hashMap.put(NICK, nickName);
            hashMap.put(BIRTHDAY, birthday);
            hashMap.put(GENDER, gender);
            hashMap.put(HEIGHT, height);
            hashMap.put(WEIGHT, weight);

            hh[0] = path;
            hh[1] = "image/jpeg";
            hh[2] = HEADER;

            fileMap = new HashMap<String[], File>();
            fileMap.put(hh, mFile);



            Log.i(TAG, "--------创建异步任务赋值--------");
        }


        /**
         * 将Bitmap对象转换为byte数组
         *
         * @param icon
         */
        private String BitmapTobytesToBase64ToString(Bitmap icon)
        {
            if (icon != null) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                icon.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                byte[] bytes = bos.toByteArray();
                return Base64.encodeToString(bytes, Base64.DEFAULT);
            }
            return null;
        }



        HttpUtil.DealResponse deal = new HttpUtil.DealResponse()
        {


            @Override
            public void dealResponse(int responseCode, InputStream input) throws IOException {
                Log.i(TAG, "响应码：" + responseCode);
                InputStreamReader reader;
                if(input != null)
                {
                    String line = null;
                    String result = "";
                    reader = new InputStreamReader(input);
                    BufferedReader br = new BufferedReader(reader);

                    while (((line = br.readLine()) != null))
                    {
                       result = result + line;
                    }

                    Log.i(TAG, "注册返回结果" + result);

                    boolean isSuccess = false;

                    try {
                        isSuccess = parserJSON(result);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    if(isSuccess)// 注册成功
                    {

                    login_Now(accounta, pwdd);



                    }

                }
            }

            @Override
            public void setHeader(String url, Object obj) {

            }
        };




        /**
         * 解析服务器返回的ＪＳＯＮ数据
         * @param result
         */
        private boolean parserJSON(String result) throws JSONException {
            JSONObject json = new JSONObject(result);
            String code = json.getString("code");
            String msg = json.getString("msg");
            if(code.equals("9003"))
            {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(EditPersionInfoActivity.this, getString(R.string.regist_ok), Toast.LENGTH_SHORT).show();
                    }
                });

                return true;
            }
            else if(code.equals("200"))
            {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(EditPersionInfoActivity.this, getString(R.string.regist_already_have), Toast.LENGTH_SHORT).show();
                    }
                });

            }
            else
            {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(EditPersionInfoActivity.this, getString(R.string.net_wrong), Toast.LENGTH_SHORT).show();
                    }
                });

            }
            return false;
        }

        @Override
        protected Boolean doInBackground(Void... params)
        {
            Log.i(TAG, "--------执行doInBackground-------");
            HttpUtil httpUtil = new HttpUtil();
            try {
                httpUtil.postDataAndImage(haveImage, MyConfingInfo.WebRegist, hashMap, fileMap, deal);
            } catch (IOException e) {
                e.printStackTrace();
            }


//            Log.i(TAG, "--------执行doInBackground-------");
//            String result = null;
//            try {
//                // Post请求的url, 与get不同，不需要带参数
//                URL url = new URL(MyConfingInfo.WebRegist);
//                Log.i(TAG, "--------执行doInBackground请求路径 + " + url.getPath());
//                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//
//                // 设置是否向connection输出，因为是post请求，参数要放在http正文，因此需要设为true
//                connection.setDoOutput(true);
//                // 设置从connection 读取
//                connection.setDoOutput(true);
//                // 设置发送方式，默认是get
//                connection.setRequestMethod("POST");
//                // post请求不能使用缓存
//                connection.setUseCaches(false);
//                // 设置执行重定向
//                connection.setInstanceFollowRedirects(true);
//                // 设置本次连接的Content-type, 配置为application/x-www-form-urlencoded
//                // 意思是正文是通过urlencoded编码过的form参数
//                // 进行编码
//                connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----testsssssss");
//                connection.setRequestProperty("Charset", "UTF-8");
//                // 连接，从openConection至此的配置必须在要connecte前完成
//                connection.connect();
//
//                // connection.getOutputStream()方法会隐含的调用connect，所以上面的connect也可不掉用
//
//                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//
//
//                out.writeBytes(content);
//                out.flush();
//                out.close();
//
//                // 在调用getInputStream()函数是才把准备好的http请求发给服务器
//                // 调用httpURLConnection的连接对象的getInputStream方法，
//                // 此方法将内存缓存区封装好的完整的http请求电文发送到服务端
//                InputStream in = connection.getInputStream();        // <=== 实际发送请求的代码就在这里面
//                InputStreamReader reader = new InputStreamReader(in);
//                Log.i(TAG, "--------从输入流读取数据");
//                int c = 0;
//                while ((c = reader.read()) != -1)
//                {
//                    result = result + (char) c;
//                }
//
//                Log.i(TAG, "--------注册结果：" + result);
//
//                connection.disconnect();
//                reader.close();
//
//
//            } catch (MalformedURLException e) {
//                Log.i(TAG, "--------执行doInBackground + -------catch1" + result);
//                e.printStackTrace();
//            } catch (IOException e) {
//                Log.i(TAG, "--------执行doInBackground + -------catch2" + result);
//                e.printStackTrace();
//            }
//
//            Log.i(TAG, "--------执行doInBackground + -------" + result);
            return null;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
        }
    }


    private void writeToSP(String key, String value) {
        LocalDataSaveTool.getInstance(EditPersionInfoActivity.this).writeSp(key, value);
    }


    private void savePersionToSP(String nickN, String emailN,
                                 String birthdayN, String heightN,
                                 String weightN, int gender) {
        writeToSP(MyConfingInfo.USER_NICK, nickN);
        writeToSP(MyConfingInfo.USER_BIRTHDAY, birthdayN);
        writeToSP(MyConfingInfo.USER_EMAIL, emailN);
        writeToSP(MyConfingInfo.USER_HEIGHT, heightN);
        writeToSP(MyConfingInfo.USER_WEIGHT, weightN);
        writeToSP(MyConfingInfo.USER_GENDER, gender + "");
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_persion, menu);
        return true;
    }
//---------------------------------------------------------------------------

    OnWheelScrollListener scrollListener = new OnWheelScrollListener() {

        @Override
        public void onScrollingStarted(WheelView wheel) {

        }

        @Override
        public void onScrollingFinished(WheelView wheel) {
            int n_year = year.getCurrentItem() + 1950;// 楠烇拷
            int n_month = month.getCurrentItem() + 1;// 閺堬拷
            initDay(n_year, n_month);
        }
    };

    WheelView year;
    WheelView month;
    WheelView day;
    PopupWindow mPopupWindow;

    /**
     * @return
     */

    private View getDataPick() {

        Calendar c = Calendar.getInstance();     // 日期对象
        int curYear = c.get(Calendar.YEAR);
        int curMonth = c.get(Calendar.MONTH) + 1;//通过Calendar算出的月数要+1
        int curDate = c.get(Calendar.DATE);
        final View view = LayoutInflater.from(EditPersionInfoActivity.this).inflate(R.layout.datapick, null);

        year = (WheelView) view.findViewById(R.id.year);
        year.setAdapter(new NumericWheelAdapter(1950, curYear));// 参数一：最小年限。参数二：最大年限
        year.setLabel("年");
        year.setCyclic(true);
        year.addScrollingListener(scrollListener);

        month = (WheelView) view.findViewById(R.id.month);
        month.setAdapter(new NumericWheelAdapter(1, 12, "%02d"));
        month.setLabel("月");
        month.setCyclic(true);
        month.addScrollingListener(scrollListener);

        day = (WheelView) view.findViewById(R.id.day);
        initDay(curYear, curMonth);
        day.setLabel("日");
        day.setCyclic(true);

        year.setCurrentItem(curYear - 1950);
        month.setCurrentItem(curMonth - 1);
        day.setCurrentItem(curDate - 1);

        Button bt = (Button) view.findViewById(R.id.set);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String mm = null;
                int months = month.getCurrentItem() + 1;
                if(months < 10)
                {
                    mm = "0" + months;
                }
                else
                {
                    mm = String.valueOf(months);
                }




                String str = (year.getCurrentItem() + 1950) + "-" + mm + "-" + (day.getCurrentItem() + 1);
//                Toast.makeText(EditPersionInfoActivity.this, str, Toast.LENGTH_LONG).show();
                birthday.setText(str);
                mPopupWindow.dismiss();
            }
        });
        Button cancel = (Button) view.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
            }
        });
        return view;
    }


    /**
     */
    private void initDay(int arg1, int arg2) {
        day.setAdapter(new NumericWheelAdapter(1, getDay(arg1, arg2), "%02d"));
    }

    /**
     * @param year
     * @param month
     * @return
     */
    private int getDay(int year, int month) {
        int day = 30;
        boolean flag = false;
        switch (year % 4) {
            case 0:
                flag = true;
                break;
            default:
                flag = false;
                break;
        }
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                day = 31;
                break;
            case 2:
                day = flag ? 29 : 28;
                break;
            default:
                day = 30;
                break;
        }
        return day;
    }
}
